package com.xxxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxy.dao.ExaminationPaperDao;
import com.xxxy.dao.KnowledgePointDao;
import com.xxxy.dao.StudentAnswerDao;
import com.xxxy.exception.MyException;
import com.xxxy.model.ExaminationPaper;
import com.xxxy.model.KnowledgePoint;
import com.xxxy.model.StudentAnswer;
import com.xxxy.response.GradeAnalysisResponse;
import com.xxxy.response.KnowledgePointResponse;
import com.xxxy.service.KnowledgePointService;
import com.xxxy.service.StudentAnswerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author sjh
 * @date 2022/2/17 14:51
 */
@Service
public class KnowledgePointServiceImpl extends ServiceImpl<KnowledgePointDao, KnowledgePoint> implements KnowledgePointService {

    @Autowired
    KnowledgePointDao knowledgePointDao;

    @Autowired
    StudentAnswerDao studentAnswerDao;

    @Autowired
    ExaminationPaperDao examinationPaperDao;


    @Override
    public List<KnowledgePointResponse> ListTree(Integer courseId) {
        LambdaQueryWrapper<KnowledgePoint> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(KnowledgePoint::getCourseId, courseId);
        lambdaQueryWrapper.orderByAsc(KnowledgePoint::getChapter);
        lambdaQueryWrapper.orderByAsc(KnowledgePoint::getChapterPoint);
        List<KnowledgePoint> list = knowledgePointDao.selectList(lambdaQueryWrapper);
        List<KnowledgePointResponse> list1 = new ArrayList<>();

        if(list == null){
            return list1;
        }
        Map<Integer, KnowledgePointResponse> map = new HashMap<>();
        for (KnowledgePoint knowledgePoint : list) {
            KnowledgePointResponse knowledgePointResponse = new KnowledgePointResponse();
            BeanUtils.copyProperties(knowledgePoint, knowledgePointResponse);
            if(knowledgePointResponse.getChapterPoint() == 0){
                map.put(knowledgePointResponse.getChapter(), knowledgePointResponse);
            }
            list1.add(knowledgePointResponse);
        }

        List<KnowledgePointResponse> list2 = new ArrayList<>();
        for (KnowledgePointResponse knowledgePointResponse : list1) {
            if(knowledgePointResponse.getChapterPoint() == 0){
                list2.add(knowledgePointResponse);
            }
            else {
                KnowledgePointResponse knowledgePointResponse1 = map.get(knowledgePointResponse.getChapter());
                if(knowledgePointResponse1 == null){
                    throw new MyException("章节设置错误");
                }
                knowledgePointResponse1.getChild().add(knowledgePointResponse);
            }
        }
        return list2;
    }

    @Override
    public Map<String, String> questionsByKnowledgePoint(Integer examId) {
        //获取试卷
        ExaminationPaper examinationPaper = examinationPaperDao.selectById(examId);
        //知识点
        String[] points = examinationPaper.getPoints().split(",");
        //题目
        String[] questions = examinationPaper.getQuestions().split(",");
        Map<String, String> map = new HashMap<>();
        for(int i = 0; i< points.length; i++){
            if(map.containsKey(points[i])){
                String value = map.get(points[i]);
                value +=  ("," + questions[i].toString());
                map.put(points[i], value);
            } else {
                map.put(points[i], questions[i]);
            }
        }
        return map;
    }

    @Override
    public Map<String, Double[]> examAnalysis(Integer examId, String studentAccount) {

        LambdaQueryWrapper<StudentAnswer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StudentAnswer::getExaminationPaperId, examId);
        lambdaQueryWrapper.eq(StudentAnswer::getStudentAccount, studentAccount);
        //学生获得的分数
        String[] score_situation = studentAnswerDao.selectOne(lambdaQueryWrapper).getScoreSituation().split(",");
        //获取试卷
        ExaminationPaper examinationPaper = examinationPaperDao.selectById(examId);
        //小节分布
        String[] section = examinationPaper.getSection().split(",");
        //小节分数
        String[] section_score = examinationPaper.getSectionScore().split(",");
        //存储每道题目的分数
        String[] scoreArry = new String[Integer.parseInt(section[section.length-1])];
        int index = 0;
        for(int i = 0; i< section.length;i++){
            while(index <= Integer.parseInt(section[i])-1){
                scoreArry[index] = section_score[i];
                index ++;
            }
        }
        //知识点
        String[] points = examinationPaper.getPoints().split(",");
        Map<String, Double[]> map = new HashMap<>();
        for(int i=0; i< points.length; i++){
            Double[] doubleArry = new Double[2];
            if(map.containsKey(points[i])){
                doubleArry = map.get(points[i]);
                doubleArry[0] += Double.parseDouble(score_situation[i]);
                doubleArry[1] += Double.parseDouble(scoreArry[i]);
            } else{
                doubleArry[0] = Double.parseDouble(score_situation[i]);
                doubleArry[1] = Double.parseDouble(scoreArry[i]);
                map.put(points[i], doubleArry);
            }
        }
        return map;
    }

    @Override
    public List<GradeAnalysisResponse> getStudentGradeAnalysis(Integer courseId, Integer examId, String studentAccount) {
        List<GradeAnalysisResponse> list = new ArrayList<>();
        //知识点对应题目map
        Map<String, String> map1 = this.questionsByKnowledgePoint(examId);
        //知识点对应得分map
        Map<String, Double[]> map2 = this.examAnalysis(examId, studentAccount);
        //课程对应的知识点列表
        List<KnowledgePointResponse> list1 = this.ListTree(courseId);
        for(int i = 0; i < list1.size(); i++){
            int num = 0 ;
            GradeAnalysisResponse gradeAnalysisResponse = new GradeAnalysisResponse();
            List<KnowledgePointResponse> list2 = list1.get(i).getChild();
            List<GradeAnalysisResponse> list3 = new ArrayList<>();
            for(int j =0; j< list2.size(); j++){
                String key = list2.get(j).getChapter().toString() + "." +list2.get(j).getChapterPoint().toString();
                if(map1.containsKey(key) && num == 0){
                    gradeAnalysisResponse.setChapter(list2.get(j).getChapter());
                    gradeAnalysisResponse.setChapterPoint(0);
                    gradeAnalysisResponse.setOutline(list1.get(j).getOutline());
                    num = 1;
                }
                if(map1.containsKey(key)){
                    GradeAnalysisResponse gradeAnalysisResponse1 = new GradeAnalysisResponse();
                    gradeAnalysisResponse1.setChapter(list2.get(j).getChapter());
                    gradeAnalysisResponse1.setChapterPoint(list2.get(j).getChapterPoint());
                    gradeAnalysisResponse1.setQuestions(map1.get(key));
                    gradeAnalysisResponse1.setOutline(list2.get(j).getOutline());
                    gradeAnalysisResponse1.setLevel(map2.get(key)[0]/map2.get(key)[1]);
                    list3.add(gradeAnalysisResponse1);
                }
            }
            if(num == 1){
                gradeAnalysisResponse.setChild(list3);
                list.add(gradeAnalysisResponse);
            }
        }
        return list;
    }

    @Override
    public List<GradeAnalysisResponse> getClassOrCourseGradeAnalysis(Integer courseId, Integer examId, Integer teachingClassId) {
        List<GradeAnalysisResponse> list = new ArrayList<>();
        //知识点对应题目map
        Map<String, String> map1 = this.questionsByKnowledgePoint(examId);
        //课程对应的知识点列表
        List<KnowledgePointResponse> list1 = this.ListTree(courseId);

        LambdaQueryWrapper<StudentAnswer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(teachingClassId != null){
            lambdaQueryWrapper.eq(StudentAnswer::getTeachingClassId, teachingClassId);
        }
        lambdaQueryWrapper.eq(StudentAnswer::getExaminationPaperId, examId);
        List<StudentAnswer> studentAnswers = studentAnswerDao.selectList(lambdaQueryWrapper);
        int index = 0;
        Map<String, Double[]> map2 = new HashMap<>();
        for(StudentAnswer studentAnswer : studentAnswers){
            //知识点对应得分map
            Map<String, Double[]> map3 = this.examAnalysis(examId, studentAnswer.getStudentAccount());
            //获取key集合对象
            Set<String> keySet = map3.keySet();
            for(String keyName:keySet) {
                Double[] doubleArry = new Double[2];
                if(map2.containsKey(keyName)){
                    doubleArry = map2.get(keyName);
                    doubleArry[0] += map3.get(keyName)[0];
                    doubleArry[1] += map3.get(keyName)[1];
                } else {
                    map2.put(keyName, map3.get(keyName));
                }
            }
        }

        //与getStudentGradeAnalysis部分代码相同
        for(int i = 0; i < list1.size(); i++){
            int num = 0 ;
            GradeAnalysisResponse gradeAnalysisResponse = new GradeAnalysisResponse();
            List<KnowledgePointResponse> list2 = list1.get(i).getChild();
            List<GradeAnalysisResponse> list3 = new ArrayList<>();
            for(int j =0; j< list2.size(); j++){
                String key = list2.get(j).getChapter().toString() + "." +list2.get(j).getChapterPoint().toString();
                if(map1.containsKey(key) && num == 0){
                    gradeAnalysisResponse.setChapter(list2.get(j).getChapter());
                    gradeAnalysisResponse.setChapterPoint(0);
                    gradeAnalysisResponse.setOutline(list1.get(j).getOutline());
                    num = 1;
                }
                if(map1.containsKey(key)){
                    GradeAnalysisResponse gradeAnalysisResponse1 = new GradeAnalysisResponse();
                    gradeAnalysisResponse1.setChapter(list2.get(j).getChapter());
                    gradeAnalysisResponse1.setChapterPoint(list2.get(j).getChapterPoint());
                    gradeAnalysisResponse1.setQuestions(map1.get(key));
                    gradeAnalysisResponse1.setOutline(list2.get(j).getOutline());
                    gradeAnalysisResponse1.setLevel(map2.get(key)[0]/map2.get(key)[1]);
                    list3.add(gradeAnalysisResponse1);
                }
            }
            if(num == 1){
                gradeAnalysisResponse.setChild(list3);
                list.add(gradeAnalysisResponse);
            }
        }
        return list;
    }

}
